<template>
  <div class="content">
    <div class="title">
      <p>收货地址</p>
    </div>
    <div class="address">
      <div class="addressTitle">
        <p>新增收货地址</p>
      </div>
      <!-- 切换区域 -->
      <div class="changeArea">
        <div><span>当前配送至：</span><span>中国大陆</span></div>
        <div>
          <el-dropdown trigger="click">
            <p class="dropdown">
              切换<i class="el-icon-arrow-down el-icon-arrow-right"></i>
            </p>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>中国大陆</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 表单 -->
      <div class="form">
        <el-form
          ref="form"
          v-loading="loading"
          :model="formData"
          :rules="rules"
          labelWidth="105px"
        >
          <el-form-item label="地址信息:" prop="address">
            <el-cascader
              ref="myCascader"
              v-model="formData.address"
              :options="addressList"
              clearable
              placeholder="请选择地址"
              style="width: 340px"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <!-- 详细地址 -->
          <el-form-item
            label="详细地址:"
            prop="detailsAddress"
            style="margin-top: 20px"
          >
            <el-input
              v-model="formData.detailsAddress"
              placeholder="请输入详细地址信息，如道路、门牌号、小
区、楼栋号、单元等信息"
              style="width: 340px"
              type="textarea"
            ></el-input>
          </el-form-item>
          <!-- 收货人姓名 -->
          <el-form-item
            label="收货人姓名:"
            prop="receiver"
            style="margin-top: 20px"
          >
            <el-input
              v-model="formData.receiver"
              placeholder="请输入收货人姓名"
              style="width: 340px"
            ></el-input>
          </el-form-item>
          <!-- 手机号码 -->
          <el-form-item label="手机号码" prop="mobile" style="margin-top: 20px">
            <el-input
              v-model="formData.mobile"
              class="input-with-select"
              placeholder="请输入您的手机号码"
              style="width: 340px"
            >
              <el-select
                slot="prepend"
                v-model="select"
                placeholder="请选择"
                size="small"
                style="width: 140px"
              >
                <el-option label="中国大陆 +86" value="1"></el-option>
                <el-option label="中国大陆 +87" value="2"></el-option>
                <el-option label="中国大陆 +88" value="3"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <!-- 复选框 -->
          <el-form-item labelWidth="10px" style="margin-top: 20px">
            <el-checkbox
              v-model="formData.isDefault"
              :false-label="0"
              :true-label="1"
            >设置为默认收货地址
            </el-checkbox>
          </el-form-item>
          <!-- 确认按钮 -->
          <el-form-item labelWidth="10px" style="margin-top: 10px">
            <el-button class="btn" type="primary" @click="handleOK('form')"
            >确认
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table">
        <div v-if="!detailedAddresList.length && !isLoading">
          <img alt="" src="./images/缺省页.png" style="margin-left: 300px" />
          <p style="margin-left: 400px; font-size: 14px; color: #626262">
            暂时没有搜索到您要找的内容！
          </p>
        </div>
        <el-table
          v-else
          v-loading="isLoading"
          :data="detailedAddresList"
          :row-style="{ height: '38.5px' }"
          border
          stripe
          style="width: 100%; height: 429px"
        >
          <el-table-column
            v-model="tableData.receiver"
            label="收货人"
            prop="receiver"
            width="80"
          ></el-table-column>
          <el-table-column
            v-model="tableData.address"
            label="所在地区"
            prop="address"
            width="180"
          ></el-table-column>
          <el-table-column
            v-model="tableData.detailsAddress"
            label="详细地址"
            prop="detailsAddress"
            width="220"
          ></el-table-column>
          <!--          <el-table-column-->
          <!--            v-model="tableData.zipCode"-->
          <!--            label="邮编"-->
          <!--            prop="zipCode"-->
          <!--            width="80"-->
          <!--          ></el-table-column>-->
          <el-table-column
            v-model="tableData.mobile"
            label="电话/手机号"
            prop="mobile"
          ></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button class="btn" size="mini" @click="handleEdit(scope.row)"
              >修改
              </el-button>
              <el-button
                class="btn"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="默认">
            <template slot-scope="scope">
              <el-button
                :class="{ default: scope.row.isDefault == 1 }"
                class="btn"
                size="mini"
                @click="handleDefault(scope.row)"
              >设为默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row justify="end" type="flex">
          <el-pagination
            :current-page.sync="page"
            :page-size="size"
            :page-sizes="[10, 20]"
            :total="total"
            background
            layout="prev, pager, next, sizes"
            style="margin-top: 20px"
            @current-change="changePage"
            @size-change="changeSize"
          >
          </el-pagination>
        </el-row>

        <!-- 弹窗 -->
        <div class="dialog">
          <el-dialog
            :before-close="handleClose"
            :visible.sync="dialogVisible"
            center
            title="修改信息"
            width="40%"
          >
            <div class="dialogForm">
              <el-form
                ref="dialogForm"
                :rules="rules"
                :model="dialogData"
                labelWidth="105px"
              >
                <el-form-item label="地址信息:" prop="address">
                  <el-cascader
                    ref="add"
                    v-model="dialogData.address"
                    :options="addressList"
                    clearable
                    placeholder="请选择地址"
                    style="width: 340px"
                    @change="changeAdd"
                  ></el-cascader>
                </el-form-item>
                <!-- 详细地址 -->
                <el-form-item
                  label="详细地址:"
                  prop="detailsAddress"
                  style="margin-top: 20px"
                >
                  <el-input
                    v-model="dialogData.detailsAddress"
                    placeholder="请输入详细地址信息，如道路、门牌号、小
区、楼栋号、单元等信息"
                    style="width: 340px"
                    type="textarea"
                  ></el-input>
                </el-form-item>
                <!-- 收货人姓名 -->
                <el-form-item
                  label="收货人姓名:"
                  prop="receiver"
                  style="margin-top: 20px"
                >
                  <el-input
                    v-model="dialogData.receiver"
                    placeholder="请输入收货人姓名"
                    style="width: 340px"
                  ></el-input>
                </el-form-item>
                <!-- 手机号码 -->
                <el-form-item
                  label="手机号码"
                  prop="mobile"
                  style="margin-top: 20px"
                >
                  <el-input
                    v-model="dialogData.mobile"
                    class="input-with-select"
                    placeholder="请输入您的手机号码"
                    style="width: 340px"
                  >
                    <el-select
                      slot="prepend"
                      v-model="select"
                      placeholder="请选择"
                      size="small"
                      style="width: 140px"
                    >
                      <el-option label="中国大陆 +86" value="1"></el-option>
                      <el-option label="中国大陆 +87" value="2"></el-option>
                      <el-option label="中国大陆 +88" value="3"></el-option>
                    </el-select>
                  </el-input>
                </el-form-item>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button
                class="btn"
                style="background-color: white; color: #000000"
                @click="dialogVisible = false"
              >取 消</el-button
              >
              <el-button
                :disabled="isDisabled"
                class="btn"
                type="primary"
                style="margin-left: 8px"
                @click="handleSub"
              >确 定</el-button
              >
            </span>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line import/no-cycle
import {
  addAddress,
  addressPageList,
  deleteAddress,
  setDefault,
  updateAddress
} from '@/framework/api/user'
import areaJson from './area.json'

export default {
  name: 'ProfileAddress',
  /* 注册组件 */
  components: {},
  /* 接受父组件传过来的数据 */
  props: {},

  /* 数据 */
  data() {
    return {
      isDisabled: false,
      dialogVisible: false,
      tableData: [],
      // 复选框
      checked: false,
      dialogData: {},
      // 详细收货地址列表
      detailedAddresList: [],
      select: '1',
      formData: {
        address: '',
        // 详细地址
        detailsAddress: '',
        // 收货人姓名
        receiver: '',
        // 手机号码
        mobile: '',
        // 省编码
        provinceCode: '',
        // 市编码
        cityCode: '',
        // 区编码
        districtCode: '',
        isDefault: 0,
        // 省
        province: '',
        // 市
        city: '',
        // 区
        district: ''
      },
      rules: {
        address: [{ required: true, message: '请选择地址', trigger: 'change' }],
        detailsAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        receiver: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }
        ]
      },
      addressList: areaJson,
      // 总条数
      total: 0,
      // 总页数
      pages: 1,
      // 当前页
      page: 1,
      // 每页显示条数
      size: 10,
      isLoading: true,
      loading: false
    }
  },

  /* 计算属性 */
  computed: {},

  /* 监听器 */
  watch: {},

  /* 初始化阶段 */
  created() {
    // 获取地址详细信息
    this.getDetailedAddressList(this.page, this.size)
  },

  /* 挂载阶段 */
  mounted() {},

  /* 销毁 */
  destroyed() {},

  /* 方法 */
  methods: {
    // 获取地址列表信息
    getDetailedAddressList(offset, pagesize) {
      this.isLoading = true
      addressPageList({
        offset,
        pagesize
      })
        .then((res) => {
          if (res.code === '00000') {
            this.detailedAddresList = res.data.records
            this.detailedAddresList.forEach((item) => {
              item.address = item.province + item.city + item.district
            })
            // 去除字符串的双引号
            this.total = parseInt(res.data.total)
            this.pages = parseInt(res.data.pages)
            this.isLoading = false
          }
        })
        .catch((err) => {
          this.isLoading = false
        })
    },
    changePage(val) {
      this.page = val
      this.detailedAddresList = []
      this.getDetailedAddressList(this.page, this.size)
    },
    changeSize(val) {
      this.size = val
      this.detailedAddresList = []
      this.getDetailedAddressList(this.page, this.size)
    },
    // 点击保存按钮，提交信息，重新获取详细地址列表
    handleOK(formName) {
      // 验证表单
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          // 去除表单中的 address
          delete this.formData.address
          this.formData.fullAddress =
            this.formData.province +
            this.formData.city +
            this.formData.district +
            this.formData.detailsAddress
          addAddress(this.formData)
            .then((res) => {
              if (res.code === '00000') {
                this.$message.success('添加成功')
                // 清空表单
                this.$refs[formName].resetFields()
                // 2.重新获取详细地址列表
                this.getDetailedAddressList()
                this.loading = false
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })
        }
      })
    },
    // 点击编辑按钮
    handleEdit(row) {
      this.dialogVisible = true
      this.dialogData = JSON.parse(JSON.stringify(row))
      this.dialogData.address = [
        row.provinceCode,
        row.cityCode,
        row.districtCode
      ]
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm('确认删除？')
        .then((_) => {
          deleteAddress({ id: row.id })
            .then((res) => {
              if (res.code === '00000') {
                this.$message.success('删除成功')
                // 重新获取详细地址列表
                this.getDetailedAddressList()
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })
        })
        .catch((_) => {})
    },
    // 设为默认
    handleDefault(row) {
      setDefault({ id: row.id })
        .then((res) => {
          if (res.code === '00000') {
            this.$message.success('设置成功')
            // 重新获取详细地址列表
            this.getDetailedAddressList()
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 关闭弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    handleChange(value) {
      const res = this.$refs['myCascader'].getCheckedNodes()[0].pathLabels
      this.formData.province = res[0]
      this.formData.city = res[1]
      this.formData.district = res[2]
      this.formData.provinceCode = value[0]
      this.formData.cityCode = value[1]
      this.formData.districtCode = value[2]
    },
    changeAdd(value) {
      const res = this.$refs['add'].getCheckedNodes()[0].pathLabels
      this.dialogData.province = res[0]
      this.dialogData.city = res[1]
      this.dialogData.district = res[2]
      this.dialogData.provinceCode = value[0]
      this.dialogData.cityCode = value[1]
      this.dialogData.districtCode = value[2]
      this.dialogData.detailsAddress = ''
    },
    // 确认修改
    handleSub() {
      // 去除 address字段
      delete this.dialogData.address
      if (this.dialogData) {
        this.dialogData.fullAddress =
          this.dialogData.province +
          this.dialogData.city +
          this.dialogData.district +
          this.dialogData.detailsAddress
        // 表单验证
        this.$refs['dialogForm'].validate((valid) => {
          if (!valid) return false
          updateAddress(this.dialogData)
            .then((res) => {
              if (res.code === '00000') {
                this.$message.success('修改成功')
                // 清空表单
                this.dialogData = {}
                this.dialogVisible = false
                // 重新获取详细地址列表
                this.getDetailedAddressList()
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  height: 1041px;
  background: #fff;

  .title {
    height: 62px;
    line-height: 62px;
    border-bottom: 1px solid #e9e9e9;

    p {
      margin-left: 24px;
    }
  }

  .address {
    padding: 24px;
    height: 100%;

    .addressTitle {
      p {
        font-weight: 400;
        font-size: 16px;
        text-align: left;
        color: #1289ff;
      }
    }

    .changeArea {
      width: 465px;
      height: 42px;
      line-height: 42px;
      background: #f7f7f7;
      margin-top: 16px;
      display: flex;
      justify-content: space-between;

      span:nth-child(1) {
        font-size: 16px;
        color: #adadad;
      }

      span:nth-child(2) {
        font-size: 16px;
        color: #000;
        margin-left: 6px;
      }

      .dropdown {
        display: inline-block;
        cursor: pointer;
        font-size: 14px;
        color: #1289ff;
        margin-right: 6px;

        i {
          margin-left: 6px;
        }
      }

      .el-icon-arrow-down {
        font-size: 12px;
      }
    }

    .form {
      width: 447px;
      // height: 355px;
      margin-top: 30px;

      ::v-deep .el-checkbox {
        // 选框
        .el-checkbox__inner {
          width: 16px;
          height: 16px;
          border-radius: 50%;

          // 中间的 “✔” 的位置调整
          &::after {
            left: 5px;
            top: 2px;
          }
        }
      }

      .btn {
        width: 146px;
        height: 40px;
        border-radius: 4px;
        background: #1289ff;
        font-weight: 500;
        font-size: 16px;
        color: #fff;
      }
    }

    .tip {
      width: 963px;
      height: 42px;
      line-height: 42px;
      margin-top: 10px;
      background: #edf6fc;
      font-size: 16px;

      span {
        color: #3c3c3c;
        margin-left: 12.5px;
      }

      i {
        color: #1289ff;
        margin-left: 12.5px;
      }
    }

    .table {
      width: 959px;
      margin-top: 20px;

      .btn {
        height: 26px;
      }

      .default {
        width: 75px;
        border-radius: 4px;
        background: #f2f8ff;
        border: 1px solid #3f87f7;
      }
    }

    .dialog {
      width: 400px;

      .btn {
        width: 86px;
        height: 30px;
        border-radius: 4px;
        background: #1289ff;
        font-weight: 500;
        font-size: 16px;
        color: #fff;
      }

      .dialog-footer {
        margin-left: -20px;
      }
    }
  }
}
</style>
